package com.datastructures2.背包队列栈;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * @author MaoLin Wang
 * @date 2020/2/2822:13
 */
public class Stack<Item> implements Iterable<Item> {
    private Node<Item>top;
    private int size;

    private static class Node<Item>{
        private Item item;
        private Node<Item> next;

        @Override
        public String toString() {
            return "Node{" +
                    "item=" + item +
                    ", next=" + next +
                    '}';
        }
    }
    public void push(Item item){
        if (isEmpty()){
            top=new Node<>();
            top.item=item;
        }else {
            Node<Item>oldTop=this.top;
            this.top=new Node<>();
            this.top.item=item;
            this.top.next=oldTop;
        }
        size++;
    }

    public Item pop(){
        if (isEmpty()){
            return null;
        }
        Item topItem=this.top.item;
        this.top=this.top.next;
        size--;
        return topItem;
    }

    public boolean isEmpty(){
        return top==null;
    }
    public int size(){
        return this.size;
    }
    @Override
    public Iterator<Item> iterator() {
        return new ListIterator<>(top);
    }

    private class ListIterator<Item> implements Iterator<Item> {
        private Node<Item> top;

        public ListIterator(Node<Item> top) {
            this.top = top;
        }

        @Override
        public boolean hasNext() {
            return top !=null;
        }

        @Override
        public Item next() {
            if (!hasNext()){
                throw new NoSuchElementException("没有元素");
            }else {
                Item item= top.item;
                top=top.next;
                return item;
            }
        }

    }

    public static void main(String[] args) {
        Stack<Integer>stack=new Stack<>();
        stack.push(1);
        stack.push(2);
        stack.push(12);
        stack.push(14);
        Iterator<Integer> iterator = stack.iterator();
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
        while (iterator.hasNext()){
            System.out.println(iterator.next());
        }
    }
}
